package com.mentaleye.biz.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mentaleye.service.AutoFormDataSourceService;
import com.mentaleye.util.ContextUtil;
import com.mentaleye.util.MultipleTansferUtil;
import com.mentaleye.util.VelocityUtil;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TemplateUtil
{
  public static  void  processor(String content,  Map<String, List<Map<String, Object>>> paras)
  {
    Map map = new HashMap();
    try {
      JSONObject jsonObj = JSONObject.parseObject(content);
      String template = (String)jsonObj.get("template");
      String parseHtml = (String)jsonObj.get("parse");
      JSONArray jsonArray = (JSONArray)jsonObj.get("data");
      map.put("template", template);

      String rexEg = "(<input[^>]*>)";
      Pattern p = Pattern.compile(rexEg);
      Matcher m = p.matcher(parseHtml);
      List result = new ArrayList();
      while (m.find()) {
        result.add(m.group());
      }
      int index = 0;
      for (int i = 0; i < result.size(); i++)
      {
        String ctrlExp = "(listctrl)";
        Pattern ctrlP = Pattern.compile(ctrlExp);
        Matcher ctrlM = ctrlP.matcher((CharSequence)result.get(i));
        if (ctrlM.find()) {
          for (int j = index; j < jsonArray.size(); j++) {
            JSONObject item = jsonArray.getJSONObject(j);
            if ("listctrl".equals(item.getString("leipiplugins"))) {
             GetListctrl(jsonArray.getJSONObject(j),paras);
            }
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static void GetListctrl(JSONObject item,  Map<String, List<Map<String, Object>>> paras){
    String datasource = item.getString("datasource") ;//整个列表名称
    String datasourceSql = item.getString("datasourcesql") ;//数据源
    Map<String,Object> velocityMap=new HashMap<String, Object>();
     //1查询列表
    if(StringUtils.isNotEmpty(datasourceSql)){
      AutoFormDataSourceService autoFormDataSourceService= (AutoFormDataSourceService)ContextUtil.getBean(AutoFormDataSourceService.class);
      paras.put(datasource,autoFormDataSourceService.explanSql(MultipleTansferUtil.getMybatisSql(datasourceSql)));
    }

  }

}